package evi.com.evi.fragment;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.classic.ClassicRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import evi.com.evi.R;
import evi.com.evi.activity.SearchActivity;
import evi.com.evi.adapter.DealOrderAdapter;
import evi.com.evi.application.MyApplication;
import evi.com.evi.bean.DisposeOrderBean;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.PopStringList;
import evi.com.evi.utils.SPUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 已处理
 */
public class DisposeTrueFragment extends Fragment implements OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    private View view;

    private ImageView iv_search;
    private List<DisposeOrderBean> list;

    private LinearLayout ll_time;
    private TextView tv_time;
    private ImageView iv_time;
    private LinearLayout ll_progress;
    private TextView tv_progress;
    private ImageView iv_progress;

    private RecyclerView can_content_view;
    private CanRefreshLayout refresh;
    private ClassicRefreshView can_refresh_header;
    private ClassicRefreshView can_refresh_footer;

    private EditText searchText2;//搜索内容et_search
    private ImageView iv_cancel;//清除搜索内容

    private DealOrderAdapter adapter;
    private OkHttpClient client;
    private JSONUtils jsonUtil;

    private String orderStatus = "7020";
    private String dateRangeType = "1";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_dispose_true, container, false);

        if (client == null) {
            client = new OkHttpClient();
        }
        if (jsonUtil == null) {
            jsonUtil = new JSONUtils();
        }

        initView();

        return view;
    }

    private void initView() {
        iv_search = (ImageView) view.findViewById(R.id.iv_search);
        iv_search.setOnClickListener(this);
        ll_time = (LinearLayout) view.findViewById(R.id.ll_time);
        tv_time = (TextView) view.findViewById(R.id.tv_time);
        iv_time = (ImageView) view.findViewById(R.id.iv_time);
        ll_progress = (LinearLayout) view.findViewById(R.id.ll_progress);
        tv_progress = (TextView) view.findViewById(R.id.tv_progress);
        iv_progress = (ImageView) view.findViewById(R.id.iv_progress);

        can_content_view = (RecyclerView) view.findViewById(R.id.can_content_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        can_content_view.setLayoutManager(layoutManager);

        ll_time.setOnClickListener(this);
        ll_progress.setOnClickListener(this);


        can_refresh_header = (ClassicRefreshView) view.findViewById(R.id.can_refresh_header);
        can_refresh_footer = (ClassicRefreshView) view.findViewById(R.id.can_refresh_footer);

        //绑定搜索条
        searchText2 = (EditText) view.findViewById(R.id.et_search2);
        iv_cancel = (ImageView) view.findViewById(R.id.iv_search_icon2);
        iv_cancel.setOnClickListener(this);


        can_refresh_header.setRefreshingStr("正在刷新");
        can_refresh_header.setPullStr("下拉刷新");
        can_refresh_header.setReleaseStr("松手刷新");
        can_refresh_header.setCompleteStr("刷新完成");

        can_refresh_footer.setRefreshingStr("正在加载");
        can_refresh_footer.setPullStr("上拉加载");
        can_refresh_footer.setReleaseStr("松手加载更多");
        can_refresh_footer.setCompleteStr("加载完成");

        refresh = (CanRefreshLayout) view.findViewById(R.id.refresh);
        //下拉刷新
        refresh.setOnRefreshListener(this);
        //上拉加载
        refresh.setOnLoadMoreListener(this);
        //刷新样式
        refresh.setStyle(0, 0);


        list = new ArrayList<>();

        adapter = new DealOrderAdapter(getActivity(), list);
        can_content_view.setAdapter(adapter);
        getInfo();

        searchText2.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                Log.e("DisposeTrueFragment","onTextChanged."+charSequence.toString()+",i="+i+",i1="+i1+",i2="+i2);
                adapter.getFilter().filter("" + charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search_icon2:
                searchText2.setText("");
                break;
            case R.id.iv_search:        //搜索
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("ActType", 2);
                startActivity(intent);
                break;

            case R.id.ll_time:        //日期
                String[] id = new String[]{"1", "2", "3", "4"};
                String[] content = new String[]{"今日订单", "近一个月", "近三个月", "近一年"};
                new PopStringList(getActivity(), "日期", content, id, new PopStringList.Stringcallback() {
                    @Override
                    public void sure(String chosed, String id) {
                        if (id != null && !id.equals(dateRangeType)) {
                            dateRangeType = id;
                            getInfo();
                        }
                        tv_time.setText(chosed);
                        //ToastUtils.showMsg(getActivity(), "content:"+chosed + "|id:" +id);
                    }
                }, 1, ll_time);
                break;

            case R.id.ll_progress:        //进度
                String[] id2 = new String[]{"7040", "7050", "7060", "7070", ""};
                String[] content2 = new String[]{"未取货", "送货中", "订单完成", "已取消订单", "全部"};
                new PopStringList(getActivity(), "进度", content2, id2, new PopStringList.Stringcallback() {
                    @Override
                    public void sure(String chosed, String id) {
                        if (id != null && !id.equals(orderStatus)) {
                            orderStatus = id;
                            getInfo();
                        }
                        tv_progress.setText(chosed);
                        //ToastUtils.showMsg(getActivity(), "content:"+chosed + "|id:" +id);
                    }
                }, 2, ll_progress);
                break;
            default:
                break;
        }
    }

    public void getInfo() {
//        dialog = AppUtils.getLoadingDialog(getActivity(), "提示", "正在查询订单，请稍后");
//        dialog.show();
//        Log.e("ee url==",ContentUtils.queryHistOrder_url+"?dateRangeType="+dateRangeType+"&orderStatus=" +orderStatus);

        if (client == null) {
            client = new OkHttpClient();
        }

        if(pages == 0){
            list.clear();
            adapter.notifyDataSetChanged();
        }


        String token = SPUtil.getString(MyApplication.getInstance().getApplicationContext(), "token");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.queryHistOrder_url + "?dateRangeType=" + dateRangeType + "&orderStatus=" + orderStatus)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ConnectUtil.isConnect(getActivity())) {
//                            toast("网络信号不佳，加载失败");
                            Toast.makeText(getActivity(), "网络信号不佳，加载失败", Toast.LENGTH_SHORT).show();
                        } else {
//                            toast("网络未联接，请检查");
                            Toast.makeText(getActivity(), "网络未联接，请检查", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(getActivity(), "网络信号不佳，加载失败", Toast.LENGTH_SHORT).show();
//                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    final JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray ary = jsonObject.getJSONArray("data");
//                        list.clear();
                        adapter.clearResult();
                        if (ary != null) {
//                            Log.e("DisposeTrueFragment", "取历史订单成功:" + ary.size());
                            for (int i = 0; i < ary.size(); i++) {
                                JSONObject obj = ary.getJSONObject(i);
//                                list.add(new DisposeOrderBean(obj) );
                                adapter.addResult(new DisposeOrderBean(obj));
                            }
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyDataSetChanged();
                                if (searchText2 == null || searchText2.getText().length() == 0) {
                                    adapter.notifyDataSetChanged();
                                } else {
                                    adapter.getFilter().filter("" + searchText2.getText().toString());
                                }
//                                dialog.dismiss();
                            }
                        });

                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
//                                dialog.dismiss();
                            }
                        });

                    }
                }
                Log.e("DisposeTrueFragment", "取历史订单成功" + jsonData);
            }
        });

    }

    @Override
    public void onRefresh() {

        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages = 0;
//                list.clear();
//                adapter.notifyDataSetChanged();
                getInfo();
                refresh.refreshComplete();
            }
        }, 1000);
    }

    private int pages;

    @Override
    public void onLoadMore() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages++;
                getInfo();
                can_refresh_footer.setCompleteStr("");
                refresh.loadMoreComplete();
            }
        }, 1000);

    }
}
